Shake or Fall to Lose

Introduction

Let’s detect a loss when the micro:bit shakes or drops!

A graphic depicting a sad micro:bit after loss

Step 2

We ‘ll start by adding code to the ||input:on shake|| container already in the workspace.

💡 You can also click the arrow next to ||input:shake|| and change the action to ||input:free fall|| or another event in the library.

input.onGesture(Gesture.Shake, function() { })

Step 3

Open the ||basic:Basic|| category
and drag ||basic:show string ["Loss"]||
into the empty ||input:on shake|| container to display a message.

input.onGesture(Gesture.Shake, function() {
    basic.showString("Loss")
})

Step 4

Click the little white circle in the simulator next to SHAKE to give your code a try.

An image of the word SHAKE above the B button

Step 5

Add some drama with music.

Open the ||music:Music|| category and
drag ||music:play [melody] [in background]||
into the top of the ||input:on shake|| container in the workspace.

input.onGesture(Gesture.Shake, function() {
    music._playDefaultBackground(music.builtInPlayableMelody(Melodies.Dadadadum), music.PlaybackMode.InBackground)
    basic.showString("Loss")
})

Step 6

Test again by clicking ⚬SHAKE

Your program should play a song and scroll the word “Loss”.

💡 You may need to unmute the simulator to hear your music.

Step 7

If you have a micro:bit connected, click |Download| and transfer your code.

Now you’re ready to attach your micro:bit to your project and try it out!

    music._playDefaultBackground(music.builtInPlayableMelody(Melodies.Funeral), music.PlaybackMode.InBackground)
    basic.showString("Loss")
    basic.showIcon(IconNames.Yes)
input.onGesture(Gesture.Shake, function() {})
basic.showIcon(IconNames.Yes)
input.onButtonPressed(Button.A, function () {
    music.play(music.builtinPlayableSoundEffect(soundExpression.sad), music.PlaybackMode.InBackground)
    music._playDefaultBackground(music.builtInPlayableMelody(Melodies.Funeral), music.PlaybackMode.InBackground)
    basic.showString("Loss")
})